package cn.tjad.tjad2.net.filedownload;

import android.content.Context;
import android.net.Uri;

import com.hjy.http.cache.DownloadCacheHelper;
import com.hjy.http.download.DownloadConfiguration;
import com.hjy.http.download.DownloadManager;
import com.hjy.http.download.FileType;
import com.hjy.http.download.listener.OnDownloadProgressListener;
import com.hjy.http.download.listener.OnDownloadingListener;

import java.io.File;

import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.utils.Tools;

public class FileDownloader {

    private boolean isInit = false;

    private volatile static FileDownloader instance;

    private DownloadConfiguration downloadConfiguration;

    public static FileDownloader getInstance() {
        if (instance == null) {
            synchronized (FileDownloader.class) {
                if (instance == null) {
                    instance = new FileDownloader();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        if (!isInit) {
            downloadConfiguration = new DownloadConfiguration.Builder(context.getApplicationContext())
                    .setThreadPoolCoreSize(5)
                    .setThreadPriority(Thread.NORM_PRIORITY - 1)
                    .setCacheDir(new File(TjadConsts.DOWNLOAD_FILE))
                    .build();
            DownloadManager.getInstance().init(downloadConfiguration);
            DownloadCacheHelper.getInstance().init(context);
            isInit = true;
        }
    }

    public void downloadFile(String id, String url, String fileName, OnDownloadingListener downloadingListener, OnDownloadProgressListener progressListener) {
        Uri uri = Uri.parse(url);
        if (uri == null) {
            Tools.showToast("下载地址不正确");
            return;
        }
        if (fileName == null) {
            fileName = uri.getLastPathSegment();
        }
        File path = new File(TjadConsts.DOWNLOAD_FILE);
        if (!path.exists()) {
            path.mkdirs();
        }
        String totalPath = TjadConsts.DOWNLOAD_FILE + "/" + fileName;
        File file = new File(totalPath);
        if (file.exists()) {
            file.delete();
        }
        DownloadManager.getInstance().downloadFile(FileType.TYPE_OTHER, id, url, fileName, downloadingListener, progressListener);
    }
}
